<template>
	<view class="root-container">
		<hx-navbar :config="{title: '发布二手房'}"/>
		<!-- :rules="rules" -->
		<uni-forms v-model="formData" ref="form" validate-trigger="bind" @submit="submit" err-show-type="undertext" @validate="validate">
			<uni-group title="基本信息">
				<uni-forms-item name="name" label="小区"  required>
					<select-lay :zindex="800" :value="tval3" name="name3" slabel="title" svalue="itemid" placeholder="请选择小区"
					                   :options="datalist" @selectitem="selectitem3">
					               </select-lay>
				</uni-forms-item>
				
				<uni-forms-item name="address" label="地址" required>
					<input type="text" v-model="formData.address" class="uni-input-border" placeholder="请输入地址" @input="binddata('address',$event.detail.value)">
				</uni-forms-item>
				<uni-forms-item name="enquipmentType" required label="类型">
					<uni-right-selecter :filterData="equipmentTypeOptions" :defaultSelected="equipmentTypeDefaultSelected" title="类型" @confirm="equipmentTypeChange"></uni-right-selecter>
				</uni-forms-item>
				<uni-forms-item  name="room" label="户型" required>
					<input type="text"  v-model="formData.room" class="uni-input-border" placeholder="室" @input="binddata('room',$event.detail.value)">
					
				</uni-forms-item>
				<uni-forms-item  name="hall" label="厅" required>
					<input type="text" v-model="formData.hall" class="uni-input-border" placeholder="厅" @input="binddata('hall',$event.detail.value)">
				</uni-forms-item>
				<uni-forms-item  name="toilet" label="卫" required>
					<input type="text" v-model="formData.toilet" class="uni-input-border" placeholder="卫" @input="binddata('toilet',$event.detail.value)">
				</uni-forms-item>
				<uni-forms-item name="price"  label="价格" required>
					<input type="text" v-model="formData.price" class="uni-input-border" placeholder="万元" @input="binddata('price',$event.detail.value)">
					
				</uni-forms-item>
				<uni-forms-item name="acreage"  label="面积" required  >
					
					<input type="text" v-model="formData.acreage" class="uni-input-border" placeholder="平方" @input="binddata('acreage',$event.detail.value)">
					
				</uni-forms-item>
				
				<u-form-item label="图片" prop="images" :border-bottom="false" >
					<u-upload ref="uploadRef" :header="uploadHeader" :action="uploadAction"  :max-size="5 * 1024 * 1024" max-count="9" @on-success="uploadSuccess" @on-uploaded="uploaded" @on-error="uploadError" @on-remove="uploadRemove" @on-change="uploadChange"></u-upload>
				</u-form-item>
				
				<uni-forms-item name="title" label="标题" >
					<input type="text" v-model="formData.title" class="uni-input-border" placeholder="请输入标题" @input="binddata('title',$event.detail.value)">
				</uni-forms-item>
				
				<uni-forms-item name="serviceContent" label="内容" required>
					<textarea type="text" v-model="formData.serviceContent" class="uni-textarea-border" placeholder="请输入房源详情"
							  @input="binddata('serviceContent',$event.detail.value)"></textarea>
				</uni-forms-item>
                <uni-forms-item name="truename" label="联系人" >
                	<input type="text" v-model="formData.truename" class="uni-input-border" placeholder="请输入联系人" @input="binddata('truename',$event.detail.value)">
                </uni-forms-item>
				<uni-forms-item name="phone" label="联系电话" required>
					<input type="text" v-model="formData.phone" class="uni-input-border" placeholder="请输入联系电话" @input="binddata('phone',$event.detail.value)">
				</uni-forms-item>
				


			</uni-group>
			<!-- 直接使用组件自带submit、reset 方法，小程序不生效 -->
			<!-- <button class="button" form-type="submit">Submit</button>
				<button class="button" form-type="reset">Reset</button> -->
			<view class="bottom-action">
				<button class="button" @click="resetForm">重置</button>
				<button class="button" @click="submitForm('form')">提交</button>
			</view>
		</uni-forms>
	</view>
</template>

<script>
import {getDicts,getSimpleRegions} from '@/api/system';


	export default {
	
		data() {
			return {
			provinceIdFilterData: [],
			provinceIdDefaultSelected: [],
			datalist: [],
			equipmentTypeDefaultSelected: [],
			equipmentTypeOptions:[],
			villageCity: {
				areaid: 0,
				name: '全国'
			},
			//20230620
			uploadHeader: { 'x-api-key': uni.getStorageSync('accessToken') },
			uploadAction: this.$mConfig.baseUrl +'/sale.php?s=uploadimg',
			//模拟初始数据
			tval3: "myvalue1",
			
			
			formData: {
					id: '',
					name: '',
					room: '',
					hall: '',
					toilet: '',
					acreage: '',
					address: '',
					price: '',
					serviceContent: '',
					enquipmentType: '',
					title: '',
					truename: '',
					images: '',
					phone: '',
					provinceId: '',
					cityId: '',
					districtId: '',
					username :'',
					url :'',
				
				},
				rules: {
					address: {
						rules: [{
							required: true,
							errorMessage: '请输入地址',
						}]
					},
					room: {
						rules: [{
							required: true,
							errorMessage: '请输入户型',
						}]
					},
					provinceId: {
						rules: [{
							required: true,
							errorMessage: '请选择地区',
						}]
					},
					enquipmentType: {
						rules: [{
							required: true,
							errorMessage: '请选择类型',
						}]
					},
					
					serviceContent: {
						rules: [{
							required: true,
							errorMessage: '请输入内容',
						}]
					},
					/*
					images: {
						rules: [{
							required: true,
							errorMessage: '请输入设备图片',
						}]
					},
					*/
					phone: {
						rules: [{
							required: true,
							errorMessage: '请输入联系电话',
						}]
					},
					
				}
			}
		},
		onShow() {
			let villageCity = uni.getStorageSync('villageCity');
		
			if (villageCity && this.villageCity.areaid != villageCity.areaid) {
				this.villageCity = villageCity;
				
				
			}
		},
		async onLoad() {
			uni.showLoading()
			
			let queryParams = {
				villageCity:this.villageCity.areaid
				//pagesize:20,
				//keyword:keyword
			}
			 let xiaoqulist = await this.$http.apiCall('get', '/xiaoqu.php?s=searchlist', queryParams);
			
   this.datalist = xiaoqulist;
	let equipmentTypeData = await this.$http.apiCall('get', '/sale.php?s=category');
	let equipmentTypeJson = {
		"name":'请选择',
		"type": 'hierarchy',
		"submenu": equipmentTypeData
	}
		
	this.equipmentTypeOptions = [
		equipmentTypeJson
	];						
						
							
	let provinceIds = await getSimpleRegions();
	let provinceIdJson = {
		"name": '请选择',
		"type": 'hierarchy',
		"submenu": provinceIds
	}
	
	this.provinceIdFilterData = [
		provinceIdJson
	];
			uni.hideLoading()
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
			let userInfo = uni.getStorageSync('userInfo');
			this.formData.phone = userInfo.mobile;
			this.formData.truename = userInfo.truename;
			this.formData.username = userInfo.username;
			console.log(this.formData.truename);
			
			
			
			let provinceIdRegion = this.jxb.getNearestRegion();
			if(provinceIdRegion){
				this.provinceIdDefaultSelected = [
					[provinceIdRegion.provinceIndex,provinceIdRegion.cityIndex,provinceIdRegion.districtIndex]
				]
				this.formData.provinceId = provinceIdRegion.provinceId;
				this.formData.cityId = provinceIdRegion.cityId;
				this.formData.districtId = provinceIdRegion.districtId;
			}
		},
		
		methods: {
				serviceTimeChange(data){
					if(data){
						this.formData.serviceTime = data.value
					}
					console.log(data);
				},
				
				 selectitem3(index, item) {
				                    console.log(item)
				                    if (index >= 0) {
				                        this.tval3 = item.itemid;
										this.formData.estate_name = item.title;
										this.formData.estate_id = item.itemid;
										this.formData.provinceId = item.areaid;
										console.log(this.formData.estate_id)
				                    } else {
				                        this.tval3 = ""
				                    }
				                },
				
				// 上传图片或者删除图片返回信息
				getimagesImageInfo(e) {
					console.log('返回图片信息：',e);
					if(e && e.length > 0){
						this.formData.url = e[0];
						this.formData.images = e.join(",");
					}else{
						this.formData.url = "";
						this.formData.images = "";
					}
					console.log('返回图片信息->缩略图：',this.formData.url);
					console.log('返回图片信息->图像串：',this.formData.images);
				},
				// 获取选择的地区
				provinceIdConfirm(e) {
					this.formData.provinceId = e.value[0][0];
					this.formData.cityId = e.value[0][1];
					this.formData.districtId = e.value[0][2];
				},
				equipmentTypeChange(e) {
					this.formData.enquipmentType = e.value[0][0];
				
				},
				createTimeDateChange: function(e) {
					this.formData.createTime = e.detail.value
				},

			/**
			 * 触发校验
			 * @param {Object} event
			 */
			validate(event) {
				// TODO 返回校验结果
				console.log('触发校验：', event);
			},

			/**
			 * 表单提交
			 * @param {Object} event
			 */
			async submit(event) {
				const {
					errors,
					value
				} = event.detail
				if (errors) {
					console.log(value);
					console.error('验证失败', errors);
					return
				}
				let lists = [];
				let images = [];
				lists = this.$refs.uploadRef.lists.filter(item => {
					return item.progress == 100;
				});
				
				lists.forEach((list, index) => {
					if (list.response) {
						images.push(list.response.data.url);
					} else {
						images.push(list.url);
					}
				});
				
				this.formData.images = images;
				let res = await this.$http.apiCall('post', '/sale.php?s=save_second', JSON.stringify(this.formData));
				console.log(res);
				if(res === 1){
					uni.showToast({
						title: `提交成功`,
						icon: 'none'
					})
					this.$mRouter.redirectTo({ route: '/pages/user/sale/list' });
					console.log("表单的值:", value);
				}
			},

			/**
			 * 手动提交
			 * @param {Object} form
			 */
			submitForm(form) {
				this.$refs[form].submit()
			},
			uploadSuccess(data, index, lists, name) {
				//this.$mHelper.toast('上传成功！');
			},
			uploaded(lists, name) {
				//this.$mHelper.toast('上传完成！');
				/* this.item.images = [];
				
				for (var item of lists) {
					if (item.error == false) {
						this.item.images.push(item.response.data.url);
					}
				} */
			},
			uploadError(res, index, lists, name) {
				this.$mHelper.toast('上传失败！');
			},
			uploadRemove(index, lists, name) {
			
			},
			uploadChange(res, index, lists, name) {
				
			},
			/**
			 * 手动重置表单
			 */
			resetForm() {
				this.$refs.form.resetFields()
			},
			/**
			 * 部分表单校验
			 * @param {Object} form
			 */
			validateField(form) {
				this.$refs[form].validateField(['name', 'email'], (errors) => {
					console.log(errors);
					if (errors) {
						uni.showToast({
							title: '验证成功'
						})
					}
				})
			},

			/**
			 * 清除表单校验
			 * @param {Object} form
			 * @param {Object} name
			 */
			clearValidate(form, name) {
				if (!name) name = []
				this.$refs[form].clearValidate(name)
			}
		}
	}
</script>

<style>
	.root-container{
		margin-bottom: 80px;
	}
	/* 头条小程序组件内不能引入字体 */
	/* #ifdef MP-TOUTIAO */


	/* #endif */
	/* #ifndef APP-NVUE */
	page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #efeff4;
		min-height: 100%;
		height: auto;
	}

	view {
		font-size: 14px;
		line-height: inherit;
	}

	.bottom-action {
		width: 100%;
		position: fixed;
		display: flex;
		justify-content: space-between;
		bottom: 0;
	}

	.example-info {
		padding: 15px;
		color: #3b4144;
		background: #ffffff;
	}

	.example-body {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: center;
		padding: 0;
		font-size: 14px;
		background-color: #ffffff;
	}

	/* #endif */
	.example {
		padding: 0 15px;
	}

	.example-info {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
		padding: 15px;
		color: #3b4144;
		background-color: #ffffff;
		font-size: 14px;
		line-height: 20px;
	}

	.example-info-text {
		font-size: 14px;
		line-height: 20px;
		color: #3b4144;
	}

	.example-body {
		flex-direction: column;
		padding: 15px;
		background-color: #ffffff;
	}

	.word-btn-white {
		font-size: 18px;
		color: #FFFFFF;
	}

	.word-btn {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		justify-content: center;
		border-radius: 6px;
		height: 48px;
		margin: 15px;
		background-color: #007AFF;
	}

	.word-btn--hover {
		background-color: #4ca2ff;
	}

	.example {
		padding: 0 10px 10px;
	}

	.uni-input-border,
	.uni-textarea-border {
		width: 100%;
		font-size: 14px;
		color: #666;
		border: 1px #e5e5e5 solid;
		border-radius: 5px;
		box-sizing: border-box;
	}

	.uni-input-border {
		padding: 0 10px;
		height: 35px;
	}

	.uni-textarea-border {
		padding: 10px;
		height: 80px;
	}

	.label-box {
		margin-right: 10px;
	}

	.transform-scale {
		transform: scale(0.7);
	}

	.button {
		width: 100%;
		font-size: 15px;
		margin: 10px 10px;
		background: #0081ff;
		color: white;
	}
</style>
